import { Swiper } from '../../util/swiper';
import { Slider } from "../../util/slider"
import { getNewsList } from '../../api/ajax';
import { formatDate } from "../../util/format";


// let swiper = new Swiper($(".swiper-wrap")).init();
let newsList = null;
let swiperArr = [];
let page = 1;

let init = () => {
    initData(page);
}

let initData = async(page) => {
    let res = await getNewsList({ page })
    let sliderObj = res.data;

    try {
        newsList = res.data;
    } catch (e) {
        initData(page)
    }

    if (page == 1 || swiperArr.length < 4) {
        swiperArr.push(...newsList.filter(item => item.imageUrls))
        if (swiperArr.length < 4) {
            initData(++page);
        } else {
            swiperArr = swiperArr.splice(0, 4)
        }
        renderSwiper();
    }

    renderSlider(sliderObj);
}


let renderSwiper = () => {
    let data = { swiperArr };
    $(".pic-wrap").html(template("swiperPic", data))
    $(".imgs-list").html(template("imgsList", data))
    new Swiper($(".swiper-wrap")).init();
}

let renderSlider = (sliderObj) => {
    let data = { sliderObj };

    template.helper('dateFormat', formatDate)

    $(".slider-bottom>ul").html(template("sliderLists", data))
    new Slider($(".slider-wrap")).init();
}






init();